extends CharacterBody2D

const Run_SPEED := 160.0
const JUMP_VELOCITY := -320.0
const FLOOR_ACCEKERATION := Run_SPEED / 0.1
const AIR_ACCEKERATION := Run_SPEED / 0.02

var gravity := ProjectSettings.get("physics/2d/default_gravity") as float;
var direction := Input.get_axis("move_Left", "move_Right") as float;


@onready var sprite_2d: Sprite2D = $Sprite2D
@onready var animation_Player: AnimationPlayer = $AnimationPlayer


func _ready() -> void:
	MessageCenter.subscribe(self, "attack", _on_attack_message)

func _physics_process(delta: float) -> void:
	direction = Input.get_axis("move_Left", "move_Right")
	var acceleration = FLOOR_ACCEKERATION if is_on_floor() else AIR_ACCEKERATION
	velocity.x = move_toward(velocity.x, direction * Run_SPEED, acceleration * delta)
	velocity.y += gravity * delta

	if is_on_floor():
		if is_zero_approx(direction) and is_zero_approx(velocity.x):
			animation_Player.play("Idle")
		else:
			animation_Player.play("Running")
		if Input.is_action_just_pressed("jump"):
			velocity.y = JUMP_VELOCITY
	else:
		animation_Player.play("Jump")

	if not is_zero_approx(direction):
		sprite_2d.flip_h = direction < 0

	
	move_and_slide()

	if Input.is_action_just_pressed("attack"):
		MessageCenter.send(self, "attack", true)


func _on_attack_message(sender: Object, attack: bool) -> void:
	if attack:
		print("attack" + " " + sender.name)
